package com.wh6648.padclock;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class FullscreenActivity extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;

    private View mContentView;
    private View mControlsView;
    private boolean mVisible;

    private Timer mTimer = new Timer();
    private Timer wTimer = new Timer();
    private TextView tvDateHh;
    private TextView tvDateMm;
    private TextView tvDateSs;
    private TextView tvDateSplit1;
    private TextView tvDateSplit2;
    private TextView tvWeather;

    private Handler wHandler = null;
    private String wContent = null;
    private Activity fullscreenActivity = this;
    private boolean isDoLight = false;
    private int lightCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_fullscreen);

        mVisible = true;
        mControlsView = findViewById(R.id.fullscreen_content_controls);
        mContentView = findViewById(R.id.fullscreen_content);
        tvDateHh = (TextView) findViewById(R.id.tv_date_hh);
        tvDateMm = (TextView) findViewById(R.id.tv_date_mm);
        tvDateSs = (TextView) findViewById(R.id.tv_date_ss);
        tvDateSplit1 = (TextView) findViewById(R.id.tv_date_split_1);
        tvDateSplit2 = (TextView) findViewById(R.id.tv_date_split_2);
        tvWeather = (TextView) findViewById(R.id.tv_weather);

        // Set up the user interaction to manually show or hide the system UI.
        mContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggle();
                //
                setLight(fullscreenActivity, 100);
                lightCount = 0;
                isDoLight = true;
            }
        });


        //http://wthrcdn.etouch.cn/weather_mini?city=大连
        //http://wthrcdn.etouch.cn/weather_mini?citykey=101070201

        setLight(this, 20);
        isDoLight = false;

        hideBottomUIMenu();

        //创建属于主线程的handler
        wHandler = new Handler();

        View v = findViewById(R.id.fullscreen_class_schedule_card);//找到你要设透明背景的layout 的id
        v.getBackground().setAlpha(230);//0~255透明度值

        //每1秒执行一次定时器中的方法，log.v打印输出。
        mTimer.schedule(mTimerTask, 0, 1000);

        //每1秒执行一次定时器中的方法，log.v打印输出。
        wTimer.schedule(wTimerTask, 0, 10 * 60 * 1000);
    }

    Runnable setLight20Task = new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
            }
            setLight(fullscreenActivity, 20);
            isDoLight = false;
            lightCount = 0;
        }
    };

    /**
     * 网络操作相关的子线程
     */
    Runnable weatherTask = new Runnable() {

        @Override
        public void run() {
            //服务器请求路径
            String strUrlPath = "http://wthrcdn.etouch.cn/weather_mini?citykey=101070201";
            //参数
            Map<String, String> params = new HashMap<String, String>();
            String strResult = HttpUtils.submitPostData(strUrlPath, params, "utf-8");
            Log.d(strResult, strResult);

            JSONObject myJsonObject = null;
            if (strResult != null && strResult.length() > 0) {
                try {
                    //将字符串转换成jsonObject对象
                    myJsonObject = new JSONObject(strResult);

                    int status = myJsonObject.getInt("status");
                    if (status == 1000) {
                        JSONObject data = myJsonObject.getJSONObject("data");
                        JSONArray forecast = data.getJSONArray("forecast");
                        if (forecast.length() > 0) {
                            Date nowDate = new Date(System.currentTimeMillis());

                            JSONObject dayWeather = (JSONObject) forecast.get(0);
                            //date
                            String date = getStringValue(dayWeather.getString("date"));
                            //type 天气
                            String type = getStringValue(dayWeather.getString("type"));
                            //fengxiang 风向
                            String fengxiang = getStringValue(dayWeather.getString("fengxiang"));
                            //fengli 风力
                            String fengli = getStringValue(dayWeather.getString("fengli"));
                            //high 最高气温
                            String high = getStringValue(dayWeather.getString("high"));
                            //low 最低气温
                            String low = getStringValue(dayWeather.getString("low"));

                            StringBuilder sb = new StringBuilder();
                            sb.append("天气预报\n\n");

                            SimpleDateFormat formatterW = new SimpleDateFormat("EEE", Locale.CHINA);
                            formatterW.setTimeZone(TimeZone.getTimeZone("GMT+08"));
                            String dateWStr = formatterW.format(nowDate);

                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
                            formatter.setTimeZone(TimeZone.getTimeZone("GMT+08"));
                            String dateStr = formatter.format(nowDate);

                            SimpleDateFormat wformatter = new SimpleDateFormat("MM/dd HH:mm:ss", Locale.CHINA);
                            wformatter.setTimeZone(TimeZone.getTimeZone("GMT+08"));
                            String updateDateStr = wformatter.format(nowDate);

                            sb.append("  星期 : " + dateWStr + "\n");
                            sb.append("  日期 : " + dateStr + "\n");
                            sb.append("  天气 : " + type + "\n");
                            sb.append("  风向 : " + fengxiang + "\n");
                            sb.append("  风力 : " + fengli + "\n");
                            sb.append("  最高 : " + high.replace("高温", "").trim() + "\n");
                            sb.append("  最低 : " + low.replace("低温", "").trim() + "\n");
                            sb.append("  更新 : " + updateDateStr + "\n");

                            wContent = sb.toString();
                            wHandler.post(runnableWeather);
                        }
                    }
                } catch (Exception e) {
                    String s = e.getMessage();
                    wContent = "";
                    wHandler.post(runnableWeather);
                }
            }
        }
    };

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableWeather = new Runnable() {
        @Override
        public void run() {
            tvWeather.setText(wContent);
        }
    };

    private String getStringValue(String input) {
        if (input != null && input.length() > 0) {
            return input.replace("<![CDATA[", "").replace("]]>", "").trim();
        }
        return "";
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }

        if (wTimer != null) {
            wTimer.cancel();
            wTimer = null;
        }
        if (wTimerTask != null) {
            wTimerTask.cancel();
            wTimerTask = null;
        }
    }

    TimerTask mTimerTask = new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Date date = new Date(System.currentTimeMillis());
                    SimpleDateFormat formatterHh = new SimpleDateFormat("HH", Locale.CHINA);
                    SimpleDateFormat formatterMm = new SimpleDateFormat("mm", Locale.CHINA);
                    SimpleDateFormat formatterSs = new SimpleDateFormat("ss", Locale.CHINA);
                    formatterHh.setTimeZone(TimeZone.getTimeZone("GMT+08"));
                    formatterMm.setTimeZone(TimeZone.getTimeZone("GMT+08"));
                    formatterSs.setTimeZone(TimeZone.getTimeZone("GMT+08"));
                    tvDateHh.setText(formatterHh.format(date));
                    tvDateMm.setText(formatterMm.format(date));
                    tvDateSs.setText(formatterSs.format(date));

                    tvDateSplit1.setText(":");
                    tvDateSplit2.setText(":");
                    if (date.getSeconds() % 2 == 0) {
                        //tvDateSplit1.setText(" ");
                        //tvDateSplit2.setText(" ");
                    }

                    if (isDoLight) {
                        lightCount++;
                        if (lightCount >= 10) {
                            setLight(fullscreenActivity, 20);
                            isDoLight = false;
                            lightCount = 0;
                        }
                    } else {
                        lightCount = 0;
                    }

                    //一分鐘
                    if (Integer.valueOf(formatterSs.format(date)) == 0) {
                        //设定闹钟的时间
                        Calendar caln = Calendar.getInstance();
                        caln.setTime(date);
                        caln.set(Calendar.HOUR_OF_DAY, 6);
                        caln.set(Calendar.MINUTE, 10);
                        caln.set(Calendar.SECOND, 0);
                        //当前时间
                        Calendar calc = Calendar.getInstance();
                        calc.setTime(date);

                        if (calc.compareTo(caln) == 0
                                && (calc.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && calc.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)) {
                            //闹钟
                            String[] times = {"06", "15"};
                            AlarmManagerUtil.setAlarm(fullscreenActivity, 0, Integer.parseInt(times[0]), Integer
                                    .parseInt(times[1]), 0, 0, "起床啦!!! 猪φ(≧ω≦*)♪ ", 1);
                        }

                        //设定闹钟的时间
                        Calendar cal20 = Calendar.getInstance();
                        cal20.setTime(date);
                        cal20.set(Calendar.HOUR_OF_DAY, 20);
                        cal20.set(Calendar.MINUTE, 0);
                        cal20.set(Calendar.SECOND, 0);

                        //设定闹钟的时间
                        Calendar cal06 = Calendar.getInstance();
                        cal06.setTime(date);
                        cal06.set(Calendar.HOUR_OF_DAY, 6);
                        cal06.set(Calendar.MINUTE, 0);
                        cal06.set(Calendar.SECOND, 0);

                        if (calc.compareTo(cal06) >= 0 && calc.compareTo(cal20) < 0) {
                            setLight(fullscreenActivity, 20);
                            isDoLight = false;
                            lightCount = 0;
                        } else if (calc.compareTo(cal20) >= 0) {
                            setLight(fullscreenActivity, 0);
                            isDoLight = false;
                            lightCount = 0;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // 开启一个子线程，进行网络操作，等待有返回结果，使用handler通知UI
                                    new Thread(setLight20Task).start();
                                }
                            });
                        }
                    }
                }
            });
        }
    };

    TimerTask wTimerTask = new TimerTask() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 开启一个子线程，进行网络操作，等待有返回结果，使用handler通知UI
                    new Thread(weatherTask).start();
                }
            });
        }
    };


    private void setLight(Activity context, int brightness) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
        context.getWindow().setAttributes(lp);
    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            hide();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mControlsView.setVisibility(View.GONE);
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
            mControlsView.setVisibility(View.VISIBLE);
        }
    };

    private final Handler mHideHandler = new Handler();
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
}
